package com.sunyur.tailor.channel.service.inner.receiveorder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.sunyur.tailor.channel.common.inner.base.SunyurListResult;
import com.sunyur.tailor.channel.common.inner.base.SunyurResult;
import com.sunyur.tailor.channel.common.inner.util.SunyurClientUtil;
import com.sunyur.tailor.channel.common.inner.util.SunyurResultUtil;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelListResultUtil;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.receiveorder.model.CreateReceiveOrderModel;
import com.sunyur.tailor.channel.service.inner.receiveorder.model.ReceiveHeadModel;
import com.sunyur.tailor.channel.service.inner.receiveorder.model.ReceiveOrderListItemModel;
import com.sunyur.tailor.channel.service.inner.receiveorder.param.CreateReceiveOrderParam;
import com.sunyur.tailor.channel.service.inner.receiveorder.param.ReceiveHeadParam;
import com.sunyur.tailor.channel.service.inner.receiveorder.param.ReceiveOrderListItemParam;
import com.sunyur.tailor.channel.service.inner.receiveorder.service.SunyurReceiveOrderService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName SunyurReceiveOrderServiceImpl
 * @Description 商越收货单服务
 * @Author yu.chen
 * @Date 2021/4/29 3:03
 * @Version 1.0
 **/
@Service("sunyurReceiveOrderService")
public class SunyurReceiveOrderServiceImpl implements SunyurReceiveOrderService {

    private static final Logger LOGGER_INFO = LoggerFactory.getLogger(SunyurReceiveOrderServiceImpl.class);
    private static final Logger LOGGER_ERROR = LoggerFactory.getLogger(SunyurReceiveOrderServiceImpl.class);

    /**
     * 请求商越Client
     */
    @Autowired
    private SunyurClientUtil sunyurClient;

    /**
     * 收货单创建 链接
     */
    @Value("${sunyur.api.createReceiveOrder}")
    private String createReceiveOrder;

    @Value("${sunyur.api.receiveItemOrder}")
    private String receiveItemOrder;

    @Value("${sunyur.api.receiveHeadOrder}")
    private String receiveHeadOrder;

    /**
     * @param createReceiveOrderParam
     * @return com.sunyur.tailor.channel.common.middle.base.ChannelResult<com.sunyur.tailor.channel.service.inner.receiveorder.model.CreateReceiveOrderModel>
     * @description 收货单创建
     * @author yu.chen
     * @date 2021/4/29 3:24
     * @Version v1.0
     */
    @Override
    public ChannelResult<CreateReceiveOrderModel> createReceiveOrder(CreateReceiveOrderParam createReceiveOrderParam) throws Exception {
        LOGGER_INFO.info("SunyurReceiveOrderServiceImpl createReceiveOrder param is {}", JSON.toJSONString(createReceiveOrderParam));
        if (ObjectUtils.isEmpty(createReceiveOrderParam)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurReceiveOrderServiceImpl createReceiveOrder param is null");
        }
        // 调用主线接口
        SunyurResult<CreateReceiveOrderModel> sunyurResult = sunyurClient.execPost(createReceiveOrder, JSON.toJSONString(createReceiveOrderParam), new TypeReference<SunyurResult<CreateReceiveOrderModel>>() {
        });
        // 主线报错
        if (!SunyurResultUtil.isSuccess(sunyurResult)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
        }
        return ChannelResultUtil.success(sunyurResult.getContent());
    }

    @Override
    public ChannelResult<List<ReceiveOrderListItemModel>> getReceiveListItem(ReceiveOrderListItemParam receiveListItemParam) throws Exception {
        LOGGER_INFO.info("SunyurReceiveOrderServiceImpl getSendOrderListItem param is {}", JSON.toJSONString(receiveListItemParam));
        if (ObjectUtils.isEmpty(receiveListItemParam) || StringUtils.isBlank(receiveListItemParam.getReceiveOrderCode())) {
            return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurOrderServiceImpl getSendOrderListItem param is null");
        }
        // 设置为每页最大条数
        receiveListItemParam.setPageSize(100);
        // 调用主线查询采购单头信息接口
        SunyurListResult<ReceiveOrderListItemModel> sunyurResult = sunyurClient.execListPost(receiveItemOrder, JSON.toJSONString(receiveListItemParam), new TypeReference<SunyurListResult<ReceiveOrderListItemModel>>() {
        });
        // 主线返回错误
        if (!SunyurResultUtil.isSuccess(sunyurResult)) {
            return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
        }
        // 判断是否存在下一页
        if (!SunyurResultUtil.isNextPage(sunyurResult)) {
            return ChannelListResultUtil.success(sunyurResult.getContent());
        }

        // 返回结果集
        List<ReceiveOrderListItemModel> ReceiveOrderListItemModelList = Lists.newArrayList();
        // 将第一次查询的结果收集
        ReceiveOrderListItemModelList.addAll(sunyurResult.getContent());
        // 循环查询剩余数据
        for (int i = receiveListItemParam.getPage() + 1; i <= sunyurResult.getTotalPage(); i++) {
            receiveListItemParam.setPage(i);
            // 调用主线查询收货行信息接口
            SunyurListResult<ReceiveOrderListItemModel> sunyurPageResult = sunyurClient.execListPost(receiveItemOrder, JSON.toJSONString(receiveListItemParam), new TypeReference<SunyurListResult<ReceiveOrderListItemModel>>() {
            });
            // 某次调用主线返回错误（小概率，可能网络等原因，此时结果集数据不完整，本次查询失败）
            if (!SunyurResultUtil.isSuccess(sunyurPageResult)) {
                LOGGER_ERROR.error("getSendOrderListItem  loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(receiveListItemParam), JSON.toJSONString(sunyurPageResult));
                return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurPageResult.getErrorMessage());
            }
            ReceiveOrderListItemModelList.addAll(sunyurPageResult.getContent());
        }
        return ChannelListResultUtil.success(ReceiveOrderListItemModelList);
    }

    @Override
    public ChannelResult<ReceiveHeadModel> getReceiveOrder(ReceiveHeadParam receiveHeadParam) throws Exception {
        LOGGER_INFO.info("SunyurReceiveOrderServiceImpl getReceiveOrder param is {}", JSON.toJSONString(receiveHeadParam));
        if (ObjectUtils.isEmpty(receiveHeadParam)) {
            return ChannelResultUtil.error(MiddleResultEnum.PARAM_NULL.getCode(), "getReceiveOrder param is null");
        }
        // 调用主线接口
        SunyurResult<ReceiveHeadModel> sunyurResult = sunyurClient.execPost(receiveHeadOrder, JSON.toJSONString(receiveHeadParam), new TypeReference<SunyurResult<ReceiveHeadModel>>() {
        });
        // 主线报错
        if (!SunyurResultUtil.isSuccess(sunyurResult)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
        }
        return ChannelResultUtil.success(sunyurResult.getContent());
    }
}
